package com.myqf.d4_线程同步.作业;

import lombok.Data;
import lombok.SneakyThrows;

public class 喝水倒水 {
    public static void main(String[] args) {
        Cup cup = new Cup();
        new Thread(new Drink(cup),"消费者").start();
        new Thread(new Waiter(cup),"服务员").start();
    }
}

@Data
class Cup {
    private int shui;
    void heshui() {
        shui-=4;
        System.out.println(Thread.currentThread().getName()+"   喝水完毕    当前水量:"+shui);
    }
    void daoshui() {
        shui+=4;
        System.out.println(Thread.currentThread().getName()+"   倒水完毕    当前水量:"+shui);
    }
}

class Drink implements Runnable {
     Cup cup;
    Drink(Cup cup) {
        this.cup = cup;
    }
    @SneakyThrows
    public void run() {
        synchronized (cup) {
            while (true) {
                cup.wait();
                cup.heshui();
                cup.notify();
            }
        }
    }
}

class Waiter implements Runnable{
     Cup cup;

    Waiter(Cup cup) {
        this.cup = cup;
    }

    @SneakyThrows
    public void run() {
        synchronized (cup) {
            while (true) {
                if (cup.getShui() < 4) {
                    cup.daoshui();
                    cup.notify();
//						Thread.currentThread().sleep(1000);
                    cup.wait();
                }
            }
        }
    }
}